import { animate, state, style, transition, trigger } from '@angular/animations';
import { Component, ElementRef, EventEmitter, HostListener, Input, OnInit, Output, Renderer2, SimpleChanges, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http';
import { NzFormatEmitEvent } from 'ng-zorro-antd/core';
import { UploadXHRArgs } from 'ng-zorro-antd/upload';

import { CaseReviewService } from '../../../../../../@core/service/case-review/case-review.service';
import { DocgenService} from '../../../../../../@core/service/case-review/doc-select/api/docgen.service';
import { ClueDataService } from '../../../../../../@core/service/clue-service/clue-data.service';
import { CaseService } from '../../../../../../@core/service/handle-service/api/case.service';
import { StakeHolderService } from '../../../../../../@core/service/handle-service/api/stakeHolder.service';
import { ApprovalInfoModel } from '../../../../../../@core/service/handle-service/model/approvalInfoModel';
import { ApprovalInfoModelCmsCase } from '../../../../../../@core/service/handle-service/model/approvalInfoModelCmsCase';
import { ApprovalInfoModelStakerHolderList } from '../../../../../../@core/service/handle-service/model/approvalInfoModelStakerHolderList';
import { SYSTEMService } from '../../../../../../@core/service/login-service/api/sYSTEM.service';
import { OrgService } from '../../../../../../@core/service/person-select-service/api/org.service';
import { ClueService } from '../../../../../../@core/service/typescript-angular-client/api/clue.service';

import {EvidenceService} from '../../../../../../@core/service/evidence/api/evidence.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DomSanitizer } from '@angular/platform-browser'; // 引入DomSanitizer服务
@Component({
  selector: 'app-docdesk',
  templateUrl: './docdesk.component.html',
  styleUrls: ['./docdesk.component.scss'],
  animations: [
    trigger('expandShrink', [
      state('expand', style({
        height: '233px',
        // opacity: 1
      })),
      state('shrink', style({
        height: '10px',
        // opacity: 0.5
      })),
      transition('shrink => expand', [
        animate('0.2s'),
      ]),
      transition('expand => shrink', [
        animate('0.2s'),
      ]),
    ]),
  ],
})
export class DocdeskComponent implements OnInit {
  @Output('expandAnimationFlag') expandAnimation = new EventEmitter<any>();
  @Input() isExpand: boolean;    
  @Input() bizfile;    
  private session = sessionStorage;
  public currentLink: any;                // 当前链接
  public expandKeys = [];                 // 默认展开的节点
  public targetOrg: string;               
  public nodes = [];    
  public listOfOption = [];
  personOptionList = [];
  getPersonSelectedValue = [];
  selectedValue = null;
  selectedPersonValue = [];
  public listOfTagOptions: any;          // 选择的审批文书
  public remark: any;                    // 子组件备注
  public id:any;
  // 
  constructor(
    public render: Renderer2,
    public http: HttpClient,             // 自定义上传证据
    public evidence: EvidenceService,    // 证据上传service
    private sanitizer: DomSanitizer,     // 安全连接service
    public caseservice: CaseService,
    public docgen: DocgenService,
    public caseReview: CaseReviewService,
    private systemService: SYSTEMService,
    private orgService: OrgService,
    private stakeHolderService: StakeHolderService,
    public clueData: ClueDataService,
    public router: Router,
    public active: ActivatedRoute,
    public clue: ClueService,
    public el:ElementRef,
    public message:NzMessageService
  ) { }

    ngOnInit() {
      this.id = this.active.snapshot.params['id'];
      if(this.active.snapshot.params['type'] =='approval'){
        let el =  this.findElement(this.el.nativeElement,'pos')[0]
        el.style.right = '30px';
      } 
      const nodesData = JSON.parse(this.session.getItem('areaData'));
      this.nodes = this.DataProcess(nodesData, '0', '机构');
      const roleInfo = JSON.parse(this.session.getItem('roles'));
      for (let i = 0; i < roleInfo.length; i++) {
        if (roleInfo[i]['roleName'] === '局长') {
          this.getDefualtHandlePerson(this.id);
        }
      }

    }

    // 用户角色为局长的时候查询默认办案人员
    getDefualtHandlePerson(id) {
      this.stakeHolderService.stakeHolderTargetCaseIdGet(id).subscribe((data) => {
        if (data['rel']) {
          this.targetOrg = data['data'][0]['targetOrgId'];
          this.selectedValue = data['data'][0]['targetDeptId'];
          this.selectedPersonValue = [data['data'][0]['targetUserId']];
          let parentId: string;
          for (let i = 0; i < this.nodes.length; i++) {
            const children = this.nodes[i]['children'];
            for (let k = 0; k < children.length; k++) {
              console.log(children[k], 'officeid');
              if (this.targetOrg === children[k]['value']) {
                parentId = children[k]['parentId'];
              }
            }
          }
          this.expandKeys = [parentId, this.targetOrg];
          this.getSelectedNodeList(this.targetOrg);
          this.getPerson(this.selectedValue);
        }
      }, (error) => {

      }); 
    }

    // 获取部分选择框选中的节点
    getSelectedValue(value): void {
      this.selectedValue = value;
      const token = this.session.getItem('accessToken') || '';
      for (let i = 0; i < this.listOfOption.length; i++) {
        if (this.listOfOption[i]['deptId'] === value) {
          this.getPerson(value);
        }
      }
    }
     // 获取人员信息
      getPerson(deptId) {
        this.systemService.authDeptUsersDeptIdGet(deptId).subscribe((res) => {
          if (res['rel'] === true) {
            this.personOptionList = [];
            for (let i = 0; i < res['data'].length; i++) {
              const obj = {realName: null, positionCode: null, userId: null, userType: null};
              obj.realName = res['data'][i]['realName'] || '';
              obj.positionCode = res['data'][i]['positionCode'] || '';
              obj.userId = res['data'][i]['userId'] || '';
              obj.userType = res['data'][i]['roles'] || [];
              this.personOptionList.push(obj);
            }
          }
        }, (error) => {
        });
      }

    // 获取树中选中的节点
    getSelectedNodeList(key): void {
      this.systemService.authOrgDeptsOrgIdGet(key).subscribe((res) => {
        if (res['rel']) {
          this.listOfOption = res['data'];
        }
      }, (error) => {
      });
    }

    DataProcess(data, parentId, type) {
      const arrayList = [];
      for (let i = 0; i < data.length; i++) {
        if (data[i]['orgTypeName'] === type && data[i]['orgParentId'] === parentId) {
          const obj = {
            title: '',
            text: '',
            value: '',
            key: '',
            parentId: '',
            children: [],
          };
          obj.title = data[i]['orgName'] || '';
          obj.text = data[i]['orgName'] || '';
          obj.value = data[i]['orgId'] || '';
          obj.key = data[i]['orgId'] || '';
          obj.parentId = data[i]['orgParentId'] || '';
          obj.children = this.DataProcess(data, obj.value, '机构');
          if (obj.children.length <= 0) {
            obj['isLeaf'] = true;
          }
          arrayList.push(obj);
        }
      }
      return arrayList;
    }

    selectedPerson(users: []) {
      
    } 

    back() {
      if(this.active.snapshot.data.type == 'handle'){
        this.router.navigate(['/main/home/handle']);
      }else if(this.active.snapshot.data.type == 'approval'){
        this.router.navigate(['/main/home/approval']);
      }else {
        this.router.navigate(['/main/home/handle']);
      }
    }

    findArea(areas,parentId,areaName,areaId){
        for(let i = 0; i<areas.length;i++){
           if(areas[i].areaParentId == parentId){
               areaName.push(areas[i].areaName);
               areaId.push(areas[i].areaId);
               this.findArea(areas,areas[i].areaId,areaName,areaId) 
           }
        }
    }
    findAreaCode(areas,areaId){
      for(let i =0;i<areas.length;i++){
        if(areas[i].areaId == areaId){
            return areas[i].areaCode;
        }
      }
    }
    mysubmit(){
      const id = this.id;
      const currentLink = this.currentLink;
      const currentHandlePerson: any[] = this.selectedPersonValue;
      const remark = this.remark;
      const approvalDocStr = this.listOfTagOptions ? this.listOfTagOptions.join(',') : '';
      const targetOrgId = this.targetOrg;
      const targetDeptId = this.selectedValue;
      let sourceOrgId = '';
      let sourceDeptId = '',sourceOrgName = '',areaName=[],areaId=[];
         // 获取部门
         let departments =  JSON.parse(this.session.getItem('departments'));
         // 获取机构
         let organization = JSON.parse(this.session.getItem('organizations'))[0];
         // 获取行政区划
         let areas = JSON.parse(this.session.getItem('areas'));
         sourceOrgId = organization['orgId']
         sourceOrgName = organization['orgName'];
         this.findArea(areas,'0',areaName,areaId) 
          const cmsCase: ApprovalInfoModelCmsCase = {
            id,
            currentHandlePerson: this.selectedPersonValue[0],
            remark,
            approvalDocStr,
    
          };
      const stakerHolderList: ApprovalInfoModelStakerHolderList[] = [];
      for (let i = 0; i < currentHandlePerson.length; i++) {
        const obj: ApprovalInfoModelStakerHolderList = {
          sourceOrgId,  
          sourceDeptId,
          sourceUserId: this.session.getItem('userId'),
          targetOrgId,
          targetDeptId,
          targetUserId: '',
          stage: currentLink,
          userType: null,
          serial: (i + 1).toString(),
        };
        const userType: any[] = [];
        for (let j = 0; j < this.personOptionList.length; j++) {
          if (this.personOptionList[j]['userId'] === currentHandlePerson[i]) {
            const role = this.personOptionList[j]['userType'];
            for (let k = 0; k < role.length; k++) {
              userType.push(role[k]['roleName']);
            }
            obj['userType'] = userType.join(',');
          }
        }
        obj['targetUserId'] = currentHandlePerson[i]; 
        stakerHolderList.push(obj);
      }

      const approvalInfoModel: ApprovalInfoModel = {
        cmsCase,
        stakerHolderList,
      };
      this.caseservice.caseProcessPut(approvalInfoModel).subscribe((data) => {
        if (data['rel']) {
          this.router.navigate(['/main/home/handle']);
        } else {
          alert(data['message']);
        }
      }, (error) => {
      });
    }

  // 底部卡片展开与收起
  cardToggle() {

    this.isExpand = !this.isExpand;
    this.expandAnimation.emit(this.isExpand);

  }
  // 关闭卡片
  closeCard() {
 
    this.isExpand  = false;
    this.expandAnimation.emit(this.isExpand);
  }
  // 打开卡片 
  openCard() {
    this.isExpand = true;
    this.expandAnimation.emit(this.isExpand);
  }


  // 结案
  completion(){
      this.caseservice.caseCompletionPut(this.id,this.remark).subscribe((res)=>{
        console.log(res);
        if(res){
          this.message.create('success', `结案成功`);
          this.router.navigate(['/main/home/handle']);
        }
      })
  }


  // 查询元素
  findElement(parent: any, classname: string): any[] {
    const result: any = [];
    const next = (parentChild) => {
      for (let i = 0; i < parentChild.children.length; i++) {
        if (parentChild.children[i].className === classname) {
          result.push(parentChild.children[i]);
        } else {
          next(parentChild.children[i]);
        }
      }
    };
    next(parent);
    return result;
  }
  // // 机构选择
  // onMechanismChange(event) {

  //   if (event !== null) {

  //   } else {
  //     this.dept = null;
  //     this.person = null;
  //   }
  // }
  //  // 部门选择
  //  onDeptChange(event) {
  //   if (event !== null) {

  //   } else {
  //     this.person = null;
  //   }
  //  }
  //  // 人员选择
  //  onPersonChange(event) {
  //    if (event !== null) {

  //    } else {
  //      this.clueList.address.county = null;
  //    }
  //  }

}
